/**
 *    Copyright 2009 Seth Albnaese
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.aquiferserver.client.flex 
{
	import flash.utils.ByteArray;
	import mx.utils.Base64Decoder;
	import mx.utils.Base64Encoder;
	import flash.utils.Endian;
	import flash.net.ObjectEncoding;
	
	import org.aquiferserver.client.flex.logging.Log;
	import org.aquiferserver.client.flex.logging.LogFactory;
	
	/**
	 * ...
	 * @author Seth Albanese
	 * @version $Id: SerializationCodec.as 60 2009-06-15 08:47:09Z salbanese0080@gmail.com $
	 */
	public class SerializationCodec
	{
		
		protected static var logger:Log = LogFactory.getLog( "org.aquiferserver.client.flex.SerializationCodec" );
		
		public static function serialize( value:Object ) : String
		{			
			
			if ( value == null )
			{
				throw new Error( "cannot serialize a null object" );
			}
			
			var bytes:ByteArray = new ByteArray();
			bytes.endian = Endian.BIG_ENDIAN;
			bytes.objectEncoding = ObjectEncoding.AMF3;
			
			bytes.writeObject( value );
			bytes.position = 0;
			
			var be:Base64Encoder = new Base64Encoder();			
			be.encodeBytes( bytes );
			var result:String = be.drain();
			logger.debug( "serialized " + result );
			return result;
			
		}
		
		public static function deserialize( value:String ) : *
		{
			logger.debug( "decerializing " + value );
			var dec:Base64Decoder = new Base64Decoder();
			dec.decode( value );

			var result:ByteArray = dec.drain();
			result.position = 0;
			return result.readObject();
		}
	}
	
}